import { useNavigate } from "react-router-dom";
import React, { useState, useEffect } from "react";
import { NavBar, Image, Swiper, Tabs, Typography } from "react-vant";
import request from "@/utils/request";
import { ShareO } from "@react-vant/icons";
import { connect } from "react-redux";
import Evaluate from "./Noddle/Evaluate";
import Single from "./Noddle/Single";
import Order from "./Noddle/Order";

function Noddle(props) {
  const navigate = useNavigate();

  // 获取热门商品
  const [hotdishes, setHotdishes] = useState([]);

  // 获取用户名
  const username = props.user.username;

  //获取用户订单
  const [datalist, setDatalist] = useState([]);
  const [totalList, setTotalList] = useState([]);
  //请求用户订单
  const getData = async () => {
    const { data } = await request.get("/order/list/username", {
      params: { username },
    });
    console.log("data", data.data);
    setTotalList(data.data);
    const newdatalist = data.data.map((item) => {
      // console.log(item);
      return JSON.parse(item.dishes);
    });
    setDatalist(newdatalist);
  };

  // 初始化加载数据
  useEffect(() => {
    if (!props.user.username) {
      navigate("/login");
    }
    request
      .get(`/menu/selCategory`, {
        params: {
          size: 5,
          category: "招牌",
        },
      })
      .then(({ data }) => {
        setHotdishes(data.data);
      });
  }, []);

  return (
    <div>
      <NavBar
        title="趣学面馆"
        leftText={
          props.user.username ? (
            <Typography.Text>{props.user.username}</Typography.Text>
          ) : (
            ""
          )
        }
        rightText={<ShareO />}
        onClickLeft={() => {
          // console.log(popover.current);
        }}
        onClickRight={() => {
          props.logout();
          navigate("/login");
        }}
      />
      {hotdishes.length != 0 ? (
        <Swiper style={{ width: "100%", height: "20vh" }} autoplay={3000}>
          {hotdishes.map((item) => (
            <Swiper.Item key={item.dishes_id}>
              <Image lazyload src={item.dishes_img} fit="cover" />
            </Swiper.Item>
          ))}
        </Swiper>
      ) : null}
      <Tabs align="start">
        <Tabs.TabPane title={`点餐`}>
          <Order getData={getData}></Order>
        </Tabs.TabPane>

        <Tabs.TabPane title={`评价`} style={{ height: "57vh" }}>
          <Evaluate username={props.user}></Evaluate>
        </Tabs.TabPane>
        <Tabs.TabPane title={`订单`}>
          <Single
            datalist={datalist}
            totalList={totalList}
            getData={getData}
          ></Single>
        </Tabs.TabPane>
      </Tabs>
    </div>
  );
}

// 获取redux用户名
// {props.user.username}
const mapStateToProps = function (state) {
  return {
    user: state.userInfo,
  };
};
const mapDispatchToProps = function (dispatch) {
  return {
    logout() {
      dispatch({ type: "logout" });
    },
  };
};
Noddle = connect(mapStateToProps, mapDispatchToProps)(Noddle);
export default Noddle;
